/*
 * ImagesManagerBean.java
 *
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package info.mikrotubula.managers;

import info.mikrotubula.db.Images;
import info.mikrotubula.db.Users;
import info.mikrotubula.db.Works;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.lang.RandomStringUtils;

/**
 *
 * @author Krystian
 */
@Stateless(mappedName="ImagesEJB")
public class ImagesManagerBean implements ImagesManagerLocal, ImagesManagerRemote {
    
    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;
    
    /** Creates a new instance of ImagesManagerBean */
    public ImagesManagerBean() {
    }

    public Images create(Integer imagePhase, String name, Users user, Works work) {
        String imageSource = generateImageSource();
        Images image = new Images(imagePhase, imageSource, name, work);
        image.setUser(user);
        return create(image);
    }
    
    public Images create(Integer imagePhase, String name, Users user) {
        String imageSource = generateImageSource();
        Images image = new Images();
        image.setImgPhase(imagePhase);
        image.setImgSource(imageSource);
        image.setImgName(name);
        image.setUser(user);
        return create(image);
    }
    
    private Images create(Images image) {
        em.persist(image);
        return image;
    }
    
    public String display(Integer imagePhase, Users user, String name) {
        Images image = new Images();
        image.setImgPhase(imagePhase);
        image.setImgName(name);
        image.setUser(user);
        Images result = (Images) em.createNamedQuery("Images.display")
                .setParameter("imgName", name)
                .setParameter("user", user)
                .getSingleResult();
        return result.getImgSource();
    }
    
    public String display(Users user, String name) {
        return display(new Integer(0), user, name);
    }    
    
    public String display(Integer userId, String name) {
        return display(new Integer(0), new Users(userId), name);
    }
    

    public List<Images> listImages(Works work) {
        return (List<Images>) em.createNamedQuery("Images.findByWork").setParameter("work",work).getResultList();
    }
    
    private String generateImageSource() {
        String result = null;
        while(result == null) {
            String test = RandomStringUtils.randomAlphanumeric(12);
            @SuppressWarnings("unchecked")
            List<Images> list = em.createNamedQuery("Images.findBySource")
                    .setParameter("source", test)
                    .getResultList();
            if (list != null && !list.isEmpty()) result = test;
        }
        return result;
    }

    
}
